package info.zlong.visibleruntime.core.mongo;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import info.zlong.visibleruntime.core.util.AddressUtils;
import info.zlong.visibleruntime.core.util.StringUtils;

public class Mongo {
    private static final int DEFAULT_PORT = 27017;
    
	private String hosts;
	private String userName;
	private String password;
	private String databaseName;
	private String collectionName;
	
	private MongoClient client;
	private MongoCollection<Document> collection;
	
	public Mongo(String hosts,String userName,String password,String databaseName,String collectionName){
		this.hosts = hosts;
		this.userName = userName;
		this.password = password;
		this.databaseName = databaseName;
		this.collectionName = collectionName;
	}
	
	public void open(){
		List<ServerAddress> seeds = getSeeds();
		List<MongoCredential> credentials = getCredentials();
		client = new MongoClient(seeds,credentials);
		
		collection = client.getDatabase(databaseName).getCollection(collectionName);
		
	}

	private List<MongoCredential> getCredentials() {
		List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(password)) {
            credentials.add(MongoCredential.createCredential(userName, "admin", password.toCharArray()));
        }
		return credentials;
	}

	public MongoClient getClient() {
		return client;
	}

	public MongoCollection<Document> getCollection() {
		return collection;
	}

	private List<ServerAddress> getSeeds() {
		List<InetSocketAddress> addrs = AddressUtils.parseAdress(hosts,  DEFAULT_PORT);
		
		List<ServerAddress> seeds = new ArrayList<ServerAddress>();
		for (InetSocketAddress addr : addrs) {
			seeds.add(new ServerAddress(addr));
		}
		return seeds;
	}
	
	public void close(){
		client.close();
	}
}
